package com.acme.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.acme.controller.HomeController;
import com.acme.dao.ChatDAO;
import com.acme.entity.Chat;
import com.acme.entity.User;

@Service
public class ChatDAOImpl implements ChatDAO {
	
//	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public List<Chat> getAllChat() {
		Query query = sessionFactory.getCurrentSession().createQuery("from Chat");
		List<?> l = query.list();
		List<Chat> chatList = new ArrayList<Chat>();
		for (Object o : l) {
			chatList.add((Chat) o);
		}
		
		return chatList;
	}
	
	@Override
	public List<Chat> getAllChatAfterTime(String time) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Chat where time > :t");	    
		query.setParameter("t", time);
		List<?> l = query.list();
		List<Chat> chatList = new ArrayList<Chat>();
		for (Object o : l) {
			chatList.add((Chat) o);
		}
		
		return chatList;
	}
	
	@Override
	public void updateChat(Chat chat, String oldTime) {
		sessionFactory.getCurrentSession().merge(chat);
		
		BigInteger oldTimeint = new BigInteger(oldTime);
		BigInteger newTimeint = new BigInteger(chat.getTime());
		BigInteger timeDifference = newTimeint.subtract(oldTimeint);
		
//		logger.info("oldTimeint value is " + oldTimeint + ". newTimeint value is " + newTimeint);
		
		Query query = sessionFactory.getCurrentSession().createQuery("delete from Chat where time < :t");
		query.setParameter("t", timeDifference.toString());
		query.executeUpdate();
	}
	
}
